// var express = require('express');
// var router = express.Router();

// /* GET users listing. */
// router.post('/', function(req, res, next) {
//   res.send('respond with a resource');
// });

// module.exports = router;
var express = require('express');
var router = express.Router();
var qiniu = require('qiniu');
var formidable = require('formidable'),
  fs = require('fs'),
  TITLE = 'formidable上传示例',
  AVATAR_UPLOAD_FOLDER = '/avatar/',
  domain = "http://localhost:3000";


//七牛
var accessKey = 'zKaJ76-Kpm8cm_KdOEi74MA5z61qS2qKXZIOoMOh';
var secretKey = 'v4aKVhbT9aVTQrNVAiIVL3O6VvJFX9WnogMJwiKf';
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

var options = {
  scope: 'images',
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);

// console.log(req.body);

var config = new qiniu.conf.Config();
// 空间对应的机房
config.zone = qiniu.zone.Zone_z0;

/* 图片上传路由 */
router.post('/', function (req, res) {

  var form = new formidable.IncomingForm();   //创建上传表单
  form.encoding = 'utf-8';        //设置编辑
  form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;     //设置上传目录
  form.keepExtensions = true;     //保留后缀
  form.maxFieldsSize = 2 * 1024 * 1024;   //文件大小

  form.parse(req, function (err, fields, files) {

    if (err) {
      res.locals.error = err;
      res.render('index', { title: TITLE });
      return;
    }
    console.log(files);

    var extName = '';  //后缀名
    switch (files.fulAvatar.type) {
      case 'image/pjpeg':
        extName = 'jpg';
        break;
      case 'image/jpeg':
        extName = 'jpg';
        break;
      case 'image/png':
        extName = 'png';
        break;
      case 'image/x-png':
        extName = 'png';
        break;
    }

    if (extName.length == 0) {
      res.locals.error = '只支持png和jpg格式图片';
      res.render('index', { title: TITLE });
      return;
    }

    var avatarName = Math.random() + '.' + extName;
    //图片写入地址；
    var newPath = form.uploadDir + avatarName;
    //显示地址；
    var showUrl = domain + AVATAR_UPLOAD_FOLDER + avatarName;
    console.log("newPath", newPath);
    console.log(files.fulAvatar.path);

    //七牛图片上传
    var localFile = files.fulAvatar.path;
    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();
    var key = avatarName;
    // 文件上传
    formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr,
      respBody, respInfo) {
      if (respErr) {
        throw respErr;
      }
      if (respInfo.statusCode == 200) {
        console.log(respBody);
        res.json(respBody);
      } else {
        console.log(respInfo.statusCode);
        console.log(respBody);
      }
    });


    // fs.renameSync(files.fulAvatar.path, newPath);  //重命名
    // res.json({
    //   "newPath":showUrl
    // });
  });
});
module.exports = router;